from typing import List
import zlib
from utils.JSON的输入和输出 import 读取json
from utils.prefixlen为1的name import prefix_1_names
from utils.文件夹下的所有文件 import getFilesList


def merge(words: List[str]) -> bytes:
    res = b''
    for word in words:
        b_word = word.encode('utf-8')
        length = len(b_word)
        if length >= 256:
            prefix1 = length // 256
            prefix2 = length % 256
            res += b'\xda' + bytes([prefix1]) + bytes([prefix2]) + b_word
        elif length >= 32:
            prefix = length
            res += b'\xd9' + bytes([prefix]) + b_word
        else:
            res += bytes([length + 160]) + b_word
    return res


def getAllWords(word_list):
    res = []
    for word in word_list:
        res.append(word['COMMAND'])
        if word['trans']:
            res.append(word['trans'])
        else:
            res.append(word['source'])
    return res


def 压缩(file_name, prefix_len: int = 3):
    with open(f'{source_path}/{file_name}', "rb") as f:
        b = f.read()  # 读取文件内容 二进制
    out = zlib.decompress(b[8:])  # 解压

    word_list: list = 读取json(f'{json_path}/{file_name}.json')  # 单词list
    new_out = out[:prefix_len] + merge(
        getAllWords(word_list))  # 这个数字需要配合IDS压缩.py的相同数字

    new_b = b[:8] + zlib.compress(new_out)
    # 保存到文件
    with open(f'output/IDS压缩/{file_name}.txt', 'wb') as f:
        f.write(new_b)


source_path = "output/IDS导出的资源/日文"
json_path = "output/IDS_To_JSON"
for name in getFilesList(source_path):
    压缩(name, 1 if name in prefix_1_names else 3)
print('success')